package com.ayoka.parenting.ui.launch;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.ayoka.parenting.Constants;
import com.ayoka.parenting.base.AppContext;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.interf.SimpleRequestCallback;
import com.ayoka.parenting.mvp.BasePresenterImpl;
import com.jincp.common.utils.AppUtils;
import com.jincp.common.utils.SharedPreferenceUtil;
import com.jincp.image.load.ImageLoader;
import com.tencent.ticsdk.core.TICManager;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: LaunchPresenter.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class LaunchPresenter extends BasePresenterImpl<LaunchContract.View> implements LaunchContract.Presenter {

    private LaunchModel model;

    private Handler handler;

    private long time = 3 * 1000;

    public LaunchPresenter() {
        model = new LaunchModel();
        handler = new Handler(Looper.getMainLooper());
    }

    public void refreshToken() {
        final String userId = UserManager.getInstance().uid;
        String refreshToken = UserManager.getInstance().refresh_token;
        model.refreshToken(this, userId, refreshToken, new SimpleRequestCallback<UserManager.TokenBean>() {
            @Override
            public void onSuccess(UserManager.TokenBean tokenBean) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                if (tokenBean == null) {
                    mView.get().onRefreshTokenCallback(false);
                    return;
                }
                UserManager.getInstance().auth_token = tokenBean.auth_token;
                UserManager.getInstance().refresh_token = tokenBean.refresh_token;
                UserManager.save();
                mView.get().onRefreshTokenCallback(true);
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().onRefreshTokenCallback(false);
            }
        });
    }

    public void cleanCache() {
        try {
            String storeVersionName = SharedPreferenceUtil.getString(Constants.APP_LOCAL_VERSION, "");
            String versionName = AppUtils.getVersionName(AppContext.getInstance());
            // 判断版本是否更新
            if (!TextUtils.equals(storeVersionName, versionName)) {
                ImageLoader.getInstance().cleanCache();
                SharedPreferenceUtil.putString(Constants.APP_LOCAL_VERSION, versionName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        long millisecond = SharedPreferenceUtil.getLong("Millisecond", 0);
        if (millisecond + 24 * 60 * 60 * 1000 < System.currentTimeMillis()) {
            ImageLoader.getInstance().cleanCache();
            SharedPreferenceUtil.putLong("Millisecond", System.currentTimeMillis());
        }
    }

    public void startCountDownTask() {
        mView.get().onCountDownTicktock((int) (time / 1000));
        handler.postDelayed(task, 1000);
    }


    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (time < 0) {
                if (!isAttached()) return;
                mView.get().onCountDownCompleted();
            } else {
                handler.postDelayed(this, 1000);
                if (!isAttached()) return;
                mView.get().onCountDownTicktock((int) (time / 1000));
            }
            time -= 1000;
        }
    };

    public void stopCountDownTask() {
        if (handler != null) {
            handler.removeCallbacks(task);
        }
        if (!isAttached()) return;
        mView.get().onCountDownCompleted();
    }

    public void loginTIC() {
        mView.get().showWaitDialog("正在登录APP...");
        String userId = UserManager.getInstance().uid;
        String userSign = UserManager.getInstance().tim_user_sig;
        TICManager.getInstance().login(userId, userSign, new TICManager.TICCallback() {
            @Override
            public void onSuccess(Object data) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().onLoginTICCallback(true);
                Log.d(TAG, "登录成功");
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().showToast("登录失败");
                mView.get().onLoginTICCallback(false);
                Log.d(TAG, "登录失败" + errMsg);
            }
        });
    }
}
